import { is } from 'immutable';
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Node extends Component {
  static propTypes = {
    node: PropTypes.object.isRequired,
    editor: PropTypes.object.isRequired,
    parent: PropTypes.object.isRequired,
    selected: PropTypes.bool
  };

  shouldComponentUpdate(nextProps) {
    if (this.props.node !== nextProps.node) {
      return true;
    }
    if (this.props.isSelected !== nextProps.isSelected) {
      return true;
    }
    if (!is(this.props.selectedPath, nextProps.selectedPath)) {
      return true;
    }
    return false;
  }

  renderNode = node => {
    const {
      editor,
      value: { selection }
    } = this.props;
    const isSelected = editor.isSelected(node);
    let selectedPath;
    if (selection.first()) {
      selectedPath = node.getPath(selection.first().key);
    }
    return (
      <Node
        selectedPath={selectedPath}
        isSelected={isSelected}
        key={node.key}
        node={node}
        parent={this.props.node}
        editor={this.props.editor}
        value={this.props.value}
      />
    );
  };

  render() {
    const { node, editor, parent, isSelected, selectedPath } = this.props;
    const children = node.nodes.toArray().map(this.renderNode);
    const attributes = { 'data-key': node.key };
    const props = {
      attributes,
      editor,
      node,
      parent,
      children,
      isSelected,
      selectedPath
    };
    const element = editor.run('renderBlock', props);
    const decorator = editor.run('renderDecorator', {
      ...props,
      children: element
    });
    if (decorator) {
      return decorator;
    }
    return element;
  }
}

export default Node;
